<template>
  <div class="app-container">
    <el-row :gutter="20" class="row">
      <el-col v-if="!isEdit" :span="6" :xs="24">
        <el-card
          v-if="activePath !== '/fileManager/upload'"
          class="box-card info"
          shadow="hover"
        >
          <el-row :gutter="20">
            <el-col :span="8"
              ><span>阅读：</span
              ><span>{{
                fileDetail.readNum ? fileDetail.readNum : 0
              }}</span></el-col
            >
            <el-col :span="8" v-if="fileDetail.allowDownload == 1"
              ><span>下载：</span
              ><span>{{
                fileDetail.downloadNum ? fileDetail.downloadNum : 0
              }}</span></el-col
            >
            <el-col :span="8">
              <span>收藏：</span
              ><span>{{
                fileDetail.collectNum ? fileDetail.collectNum : 0
              }}</span></el-col
            >
            <el-col
              :span="20"
              class="class"
              v-if="fileDetail.status === 'PUBLISH'"
            >
              <span>安全等级：</span
              ><span>{{
                fileDetail.application === '0' ? '公开' : '受控'
              }}</span>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col
              :span="8"
              class="btn"
              v-if="
                fileDetail.status === 'PUBLISH' &&
                fileDetail.path.indexOf('pdf') !== -1 &&
                fileDetail.allowPrint === '1'
              "
            >
              <el-button
                icon="Printer"
                size="medium"
                @click="printFile"
                link
                type="info"
                >打印</el-button
              >
            </el-col>
            <el-col
              :span="8"
              class="btn"
              v-if="
                fileObjExt === 'image' &&
                fileDetail.status === 'PUBLISH' &&
                fileDetail.allowPrint === '1'
              "
            >
              <el-button
                icon="Printer"
                size="medium"
                v-print="print"
                link
                type="info"
                >打印</el-button
              >
            </el-col>
            <el-col
              :span="8"
              class="btn"
              v-if="
                fileDetail.status === 'PUBLISH' &&
                fileDetail.allowDownload === '1'
              "
            >
              <el-button
                size="medium"
                link
                type="info"
                icon="download"
                @click="_downloadFile(fileDetail)"
                >下载</el-button
              >
            </el-col>
            <el-col
              :span="8"
              class="btn"
              v-if="
                fileDetail.status === 'PUBLISH' &&
                !originPathDocumentConsult &&
                fileDetail.allowUpload == 1
              "
            >
              <el-button
                size="medium"
                link
                type="info"
                icon="Upload"
                @click="_reUpload"
                >重传</el-button
              >
            </el-col>

            <el-col
              :span="8"
              class="btn"
              v-if="
                originPath &&
                !originPathDocumentConsult &&
                fileDetail.status !== 'CANCEL'
              "
            >
              <el-button
                icon="Delete"
                size="medium"
                link
                type="info"
                @click="_cancelFile"
                >作废</el-button
              >
            </el-col>
            <el-col
              :span="8"
              class="btn"
              v-if="
                fileDetail.status === 'PUBLISH' && !originPathDocumentConsult
              "
            >
              <el-button
                icon="RefreshLeft"
                size="medium"
                link
                type="info"
                @click="_revokeFile"
                >撤回</el-button
              >
            </el-col>
            <el-col
              :span="8"
              class="btn"
              v-if="
                fileDetail.status === 'CANCEL' && !originPathDocumentConsult
              "
            >
              <el-button
                icon="RefreshRight"
                size="medium"
                link
                type="info"
                @click="_reCancelFile"
                >恢复</el-button
              >
            </el-col>
            <el-col
              :span="8"
              class="btn"
              v-if="
                fileDetail.status === 'PUBLISH' && !originPathDocumentConsult
              "
            >
              <el-button
                icon="Top"
                size="medium"
                link
                type="info"
                @click="_getTop"
                >{{
                  fileDetail.topStatus === '1' ? '取消置顶' : '置顶'
                }}</el-button
              >
            </el-col>
            <el-col
              :span="8"
              class="btn"
              v-if="fileDetail.status === 'PUBLISH'"
            >
              <el-button
                size="medium"
                link
                type="info"
                icon="Aim"
                @click="_collectFile"
                >{{
                  fileDetail.collectStatus === '1' ? '取消收藏' : '收藏'
                }}</el-button
              >
            </el-col>
            <el-col
              :span="8"
              class="btn"
              v-if="
                fileObjExt === 'office' &&
                fileDetail.status === 'PUBLISH' &&
                !originPathDocumentConsult
              "
            >
              <el-button
                icon="edit"
                size="medium"
                @click="editOnline"
                link
                type="info"
                >在线编辑</el-button
              >
            </el-col>
            <!-- <el-col
              :span="8"
              class="btn"
              v-if="
                fileObjExt === 'office' &&
                fileDetail.status === 'PUBLISH' &&
                !originPathDocumentConsult &&
                proxy.$permission('publishFile:unpublish')
              "
            >
              <el-button
                icon="Finished"
                size="medium"
                @click="submitVoidFileFun"
                link type='info'
                >取消发布</el-button
              >
            </el-col> -->
            <!-- <el-col :span="8" class="btn" v-else>
              <el-button size="medium" link type='info' disabled
                >在线编辑</el-button
              >
            </el-col> -->
          </el-row>
        </el-card>
        <el-card
          v-if="
            originPath &&
            fileDetail.status === 'PUBLISH' &&
            activePath !== '/fileManager/upload'
          "
          class="box-card history"
          shadow="hover"
        >
          <template v-slot:header>
            <div class="clearfix">
              <span>历史版本</span>
            </div>
          </template>
          <div class="his-list">
            <el-empty :image-size="100" v-if="historyArr.length === 0" />
            <el-timeline class="timeline" v-else>
              <el-timeline-item
                v-for="item in historyArr"
                :timestamp="item.updateTime && item.updateTime.split(' ')[0]"
                placement="top"
              >
                <el-card shadow="hover">
                  <h4>{{ item.fileName }}</h4>
                  <p class="his-box">
                    <span>
                      {{ item.updateUser || item.publishUser }} &nbsp;|&nbsp;{{
                        item.updateTime || item.publishTime
                      }}
                    </span>
                    <el-button
                      class="his-dowload"
                      v-if="fileDetail.status === 'PUBLISH'"
                      :disabled="fileDetail.allowDownload === '0'"
                      size="medium"
                      link
                      type="info"
                      icon="download"
                      @click="_downloadFile(item)"
                      >下载</el-button
                    >
                  </p>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-card>
        <el-card v-if="isShowLife" class="box-card lifecycle" shadow="hover">
          <template v-slot:header>
            <div class="clearfix">
              <span>生命周期</span>
            </div>
          </template>
          <div class="listcycle-list">
            <el-empty :image-size="100" v-if="recordArr.length === 0" />
            <el-timeline class="timeline" v-else>
              <el-timeline-item
                v-for="item in recordArr"
                :timestamp="item.createTime"
                placement="top"
              >
                <p>
                  <span class="step">{{ item.statusText }}</span>
                  {{ item.opUser }}
                </p>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-card>
      </el-col>
      <el-col :span="!isEdit ? 18 : 24" :xs="24">
        <el-card class="box-card-right" shadow="hover">
          <template v-slot:header>
            <div class="clearfix">
              <span>
                {{ fileDetail.fileName }} &nbsp;&nbsp;&nbsp;版本号：{{
                  fileDetail.version
                }}</span
              >
              <span v-if="fileDetail.sysVersion">
                &nbsp;&nbsp;&nbsp;系统版本号：{{ fileDetail.sysVersion }}</span
              >
            </div>
          </template>
          <FileViews :fileObj="fileDetail"></FileViews>
        </el-card>
      </el-col>
    </el-row>
    <!-- S 编辑弹窗 -->
    <EditDialog
      v-if="editOpen"
      title="文档重传"
      :disabled="true"
      :open="editOpen"
      :fileObj="fileDetail"
      :uploadSetting="uploadSetting"
      :fileCateTree="fileCateTree"
      :fileCate="fileCate"
      @submit="submit"
      @close="editClose"
    ></EditDialog>
    <!-- E 编辑弹窗 -->
  </div>
</template>

<script setup name="FileView">
import EditDialog from './../uploadFile/editDialog.vue'
import { baseData } from '../index.js'
import {
  getDetail,
  cancelFile,
  revokeFile,
  collectFile,
  reCancelFile,
  cancelVoidFile,
  setDuration,
  lock,
  getHistory,
  getRecord,
  getTop,
  getCategoryListSelect,
  reUpload,
  publishVoidFile,
  getFileBlob,
  downloadFile,
} from '@/api/fileManager'
import { getFileName } from './../index.js'
import { handleTree } from '@/utils/index.js'
import { printWithUrl } from '@/utils/exportUtil.js'
import { getFileCate, getFileType } from '../index.js'

const baseURL = import.meta.env.VITE_APP_BASE_API
const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
let editOpen = ref(false)
const uploadSetting = reactive(baseData.uploadSetting)
const formList = ref(baseData.formList)
const fileDetail = ref({})
const fileCateTree = ref([])
const activePath = ref(undefined)
activePath.value = route.query.active
const id = route.query.id || route.params.id
const editStatus = route.query.mode === 'edit'
const print = ref({
  id: 'printBox', //这里的id就是上面我们的打印区域id，实现指哪打哪
  popTitle: '', // 打印配置页上方的标题
  extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  previewTitle: '', // 打印预览的标题
  previewPrintBtnLabel: '', // 打印预览的标题下方的按钮文本，点击可进入打印
  zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
  previewBeforeOpenCallback() {
    console.log('正在加载预览窗口！')
  }, // 预览窗口打开之前的callback
  previewOpenCallback() {
    console.log('已经加载完预览窗口，预览打开了！')
  }, // 预览窗口打开时的callback
  beforeOpenCallback() {
    console.log('开始打印之前！')
  }, // 开始打印之前的callback
  openCallback() {
    console.log('执行打印了！')
  }, // 调用打印时的callback
  closeCallback() {
    console.log('关闭了打印工具！')
  }, // 关闭打印的callback(无法区分确认or取消)
  clickMounted() {
    console.log('点击v-print绑定的按钮了！')
  },
})
// 是否是编辑状态
const isEdit = computed(() => {
  return route.query.mode === 'edit'
})
// 锁定文档编辑
lockFile()
function lockFile() {
  if (editStatus) {
    try {
      lock({ lock: '1', id })
    } catch (error) {}
  }
}

// 关闭浏览器或者销毁组件解锁文档编辑
window.addEventListener('beforeunload', (e) => unlock(e))
onBeforeUnmount(() => {
  unlock()
})
function unlock(e) {
  if (editStatus) {
    try {
      lock({ lock: '0', id })
    } catch (error) {}
  }
}

// 是否显示生命周期（发布文档和作废文档都会展示生命周期）
const isShowLife = computed(() => {
  return (
    (originPath && fileDetail.value.status === 'PUBLISH') ||
    (originPathCancel && fileDetail.value.status === 'CANCEL') ||
    fileDetail.value.status === 'RECOVERY'
  )
})

// 来源地址是否是作废
const originPathCancel = computed(() => {
  return route.query.active === '/fileManager/cancellation'
})

// 来源地址是否是发布文档或者我的上传
const originPath = computed(() => {
  return (
    route.query.active === '/fileManager/publish' ||
    route.query.active === '/fileManager/upload'
  )
})

// 来源地址是否是收藏文档
const isCancel = computed(() => {
  return route.query.active === '/fileManager/cancellation'
})

// 来源地址是否是作废文档
const isCollection = computed(() => {
  return route.query.active === '/fileManager/collection'
})

// 来源地址是否是文档查阅或者收藏记录
const originPathDocumentConsult = computed(() => {
  return (
    route.query.active === '/fileManager/documentConsult' ||
    route.query.active === '/fileManager/collection'
  )
})

onMounted(() => {})
onUnmounted(() => {
  _setDuration()
  clearInterval(interval)
})

let timer = ref(0)
let interval = setInterval(() => {
  timer.value++
}, 1000)
function submitVoidFileFun() {
  proxy
    .$confirm('是否确认取消发布本条数据？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      publishVoidFile([fileDetail.value.id]).then((res) => {
        if (res.success) {
          _getDetail()
          showTip()
        }
      })
    })
}

// 增加文档阅读时长
function _setDuration() {
  let timeMin = (timer.value / 60).toFixed(2)
  if (!fileDetail.value.id || !fileDetail.value.readFlowId) {
    return
  }
  setDuration({
    fileId: fileDetail.value.id,
    readFlowId: fileDetail.value.readFlowId,
    readTimeLength: timeMin,
  })
}

function _cancelFile() {
  proxy
    .$confirm('是否确认作废本条数据？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      cancelFile([fileDetail.value.id]).then((res) => {
        if (res.success) {
          fileDetail.value.status = 'CANCEL'
          _getRecord(mainId.value)
          showTip()
        }
      })
    })
    .catch(() => {})
}
function downloadUrl(url, fileName) {
  let x = new XMLHttpRequest()
  x.open('GET', url, true)
  x.responseType = 'blob'
  x.onload = function () {
    let url = window.URL.createObjectURL(x.response)
    let a = document.createElement('a')
    a.href = url
    a.download = fileName
    a.click()
  }
  x.send()
}
function _downloadFile(item) {
  downloadFile(item.id).then((res) => {
    let obj = fileDetail.value
    let id = obj.id
    let fileName = obj.fileName
    if (item) {
      id = item.fileDetailId || item.id
      fileName = item.fileName
    }
    let url = obj.path.indexOf(baseURL) === -1 ? baseURL + obj.path : obj.path
    downloadUrl(url, obj.fileName)
  })
}

function _reUpload() {
  editOpen.value = true
}

function editClose() {
  editOpen.value = false
}

// 跳转至文档编辑
function editOnline() {
  const obj = fileDetail.value
  router.push({
    path: '/fileManager/fileView/' + obj.id,
    query: {
      view: 1,
      mode: 'edit', // 编辑页面
      active: route.query.active,
    },
  })
}

let fileObjType = ref('')
function printFile() {
  let obj = fileDetail.value
  let url = obj.path
  getFileBlob(obj.path).then((res) => {
    let blob = new Blob([res], {
      type: fileObjType.value,
    })
    url = URL.createObjectURL(blob)
    printWithUrl(url)
  })
}

const fileCate = ref([])
function _getCategoryListSelect() {
  getCategoryListSelect({
    includeStop: false,
  }).then((res) => {
    const selectData = res.data
    fileCate.value = selectData
    let treeArr = handleTree(selectData, 'id')
    fileCateTree.value = treeArr
    /*  formList.value.forEach((item, index) => {
      if (item.prop === 'fileCategoryId') {
        let treeArr = handleTree(selectData, 'id')
        item.selectData = treeArr
        fileCateTree.value = treeArr
      }
    }) */
  })
}
_getCategoryListSelect()

function submit(data) {
  const params = {
    fileCode: data.fileCode,
    fileUploadId: data.detail.fileUploadId,
    notes: data.notes,
    oldFileId: data.detail.id,
    remark: data.remark,
    summary: data.summary,
    title: data.title,
  }
  const _params = Object.assign(data.detail, params)
  // 重传
  reUpload(_params).then((res) => {
    if (res.code === 200) {
      _getDetail()
      editOpen.value = false
    }
  })
}

// 撤回
function _revokeFile() {
  proxy
    .$confirm('是否确认撤回本条数据？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      revokeFile([fileDetail.value.id]).then((res) => {
        if (res.success) {
          _getDetail()
          showTip()
        }
      })
    })
    .catch(() => {})
}

// 恢复
function _reCancelFile() {
  proxy
    .$confirm('是否确认恢复本条数据？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      cancelVoidFile([fileDetail.value.id]).then((res) => {
        if (res.success) {
          fileDetail.value.status = 'RECOVERY'
          _getRecord(mainId.value)
          showTip()
        }
      })
    })
    .catch(() => {})
}

// 收藏 取消收藏
function _collectFile() {
  let collectStatus = '1'
  if (fileDetail.value.collectStatus === '1') {
    collectStatus = '0'
    fileDetail.value.collectNum -= 1
  } else {
    fileDetail.value.collectNum += 1
  }
  collectFile({
    collectStatus,
    fileId: fileDetail.value.id,
  }).then((res) => {
    if (res.success) {
      fileDetail.value.collectStatus = collectStatus
      showTip()
    }
  })
}

// 置顶 取消置顶
function _getTop() {
  let topType = '1'
  let text = '是否确认置顶本条数据？'
  if (fileDetail.value.topStatus == '1') {
    topType = '0'
    text = '是否取消置顶本条数据？'
  }

  proxy
    .$confirm(text, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      getTop(fileDetail.value.id, {
        topType,
      }).then((res) => {
        if (res.success) {
          fileDetail.value.topStatus = topType
          showTip()
        }
      })
    })
    .catch(() => {})
}
function showTip() {
  proxy.$message.success({
    message: '操作成功',
    showClose: true,
    duration: 3500,
  })
}
// 历史版本查询
const historyArr = ref([])
function _getHistory(mainId) {
  getHistory(mainId).then((res) => {
    if (res.code === 200) {
      historyArr.value = res.data
    } else {
      // proxy.$message.error('未知错误，请联系管理员!')
    }
  })
}

// 生命周期查询
const recordArr = ref([])
function _getRecord(mainId) {
  getRecord(mainId).then((res) => {
    if (res.code === 200) {
      recordArr.value = res.data
    } else {
      // proxy.$message.error('未知错误，请联系管理员!')
    }
  })
}

// 是否是office
let fileObjExt = ref('')
const mainId = ref(undefined)
function _getDetail() {
  let params = {
    id: id,
  }
  // 作废文档进入详情需要携带source参数
  if (isCancel.value) {
    params['source'] = 'cancel_list'
  }
  if (isCollection.value) {
    params['source'] = 'collection_list'
  }

  getDetail(params).then((res) => {
    // 加载完成
    if (res.code === 200) {
      fileDetail.value = res.data
      print.value.popTitle = fileDetail.value.fileName
      let path = res.data.path
      if (!path) {
        console.log('文档path缺失')
        return
      }
      fileObjExt.value = getFileCate(path)
      fileObjType.value = getFileType(path)
      mainId.value = res.data.mainId
      _getHistory(res.data.mainId)
      _getRecord(res.data.mainId)
    } else {
      // proxy.$message.error('未知错误，请联系管理员!')
    }
  })
}
// 触发刷新children路由iframe组件
watch(
  () => proxy.$store.state.template.freashIframe,
  () => {
    setTimeout(() => {
      _getDetail()
    }, 0)
  },
  {
    deep: true,
  }
)
_getDetail()
</script>
<style lang="scss">
.info {
  .el-button [class*='el-icon'] + span {
    margin-left: 0;
  }
}
</style>
<style lang="scss" scoped>
.app-container {
  font-size: 14px;
  color: rgb(96, 98, 102);
  overflow-x: hidden;
  .row {
    min-height: calc(100vh - 124px);
  }
  .his-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .class {
    margin-top: 5px;
    margin-bottom: 10px;
  }
  .btn {
    display: flex;
    align-items: center;
    margin-bottom: 4px;
    :deep(.el-button) {
      padding: 0 4px;
    }
    span {
      padding-left: 5px;
    }
  }
  .timeline {
    padding-left: 0;
    width: 95%;
  }
  .box-card:not(:first-child) {
    margin-top: 10px;
  }
  .info {
    max-height: 200px;
    overflow-y: auto;
  }
  .history {
    .his-list {
      max-height: 280px;
      overflow-x: hidden;
      overflow-y: auto;
    }
  }
  .lifecycle {
    .listcycle-list {
      max-height: 570px;
      overflow-y: auto;
    }
    .step {
      color: #409eff;
      padding-right: 10px;
    }
  }
  .box-card-right {
    position: relative;
    height: 100%;
  }
}
</style>
